<?php

$configs = C::t('#erling_filedset#er_filedset_config')->fetch_by_keys([
    'path_before', 'allowed_groups', 'max_size', 'file_types', 'file_num'
]);
// 获取当前用户组
$current_group = $_G['groupid'];

// 获取允许的用户组
$allowed_groups = dunserialize($configs['allowed_groups']['value']);
$allowed_groups = array_map('intval', $allowed_groups);

// 检查用户是否有上传权限
if(!in_array($current_group, $allowed_groups)) {
    echo json_encode(['success' => false, 'message' => '您所在的用户组没有上传权限']);
    exit;
}

// 检查当前用户已有的文件数是否大于等于系统限制
$er_filedset = C::t('#erling_filedset#er_filedset');
$file_num = $er_filedset->count_by_uid( $_G['uid']);
if($file_num >= $configs['file_num']['value']) {
    echo json_encode(['success' => false,'message' => '您已达到上传文件的数量限制（每个用户最大上传数量为：'. $configs['file_num']['value'].'）']);
    exit; 
}

if(empty($_FILES['filedset_file'])) {
    echo json_encode(['success' => false, 'message' => '请选择要上传的文件']);
    exit;
}

$file = $_FILES['filedset_file'];
$max_size = $configs['max_size']['value'] * 1024 ;
if (isset($configs['file_types']['value'])) {
    $allowed_types = is_array($configs['file_types']['value']) 
        ? $configs['file_types']['value'] 
        : explode(',', $configs['file_types']['value']);
} else {
    $allowed_types = ['txt']; // 默认值
}

// 检查文件大小
if($file['size'] > $max_size) {
    echo json_encode(['success' => false, 'message' => '文件大小超过限制']);
    exit;
}

// 检查文件类型
$file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if(!in_array($file_ext, $allowed_types)) {
    echo json_encode(['success' => false, 'message' => '不支持的文件类型']);
    exit;
}

// 创建上传目录
$upload_dir = dirname(__FILE__) . '/../20cms/';
if(!is_dir($upload_dir)) {
    if(!mkdir($upload_dir, 0755, true)) {
        echo json_encode(['success' => false, 'message' => '无法创建上传目录']);
        exit;
    }
}

// 检查是否是覆盖上传
$is_cover = false;
$cover_file_id = isset($_POST['file_id']) ? intval($_POST['file_id']) : 0;
$cover_file_info = [];
$new_filename = '';
if($cover_file_id > 0) {
    $er_filedset = C::t('#erling_filedset#er_filedset');
    $cover_file_info = $er_filedset->fetch_by_id($cover_file_id);
    
    if($cover_file_info && $cover_file_info['uid'] == $_G['uid']) {
        $is_cover = true;
        // 从原文件URL中提取文件名
        $url_parts = explode('/', $cover_file_info['url']);
        $new_filename = end($url_parts);
    }
}

// 生成唯一文件名（如果不是覆盖上传）
if(!$is_cover) {
    $new_filename = uniqid() . '.' . $file_ext;
}
$destination = $upload_dir . $new_filename;

// 移动文件
if (isset($configs['path_before']['value']) && is_string($configs['path_before']['value'])) {
    $decoded = json_decode($configs['path_before']['value'], true);
    if (json_last_error() === JSON_ERROR_NONE) {
        $configs['path_before']['value'] = $decoded;
    }
}
if(move_uploaded_file($file['tmp_name'], $destination)) {
    if(!empty($configs['path_before']['value'])) {
        // 处理数组形式的 path_before
        if (is_array($configs['path_before']['value'])) {
            $paths = array_filter($configs['path_before']['value']); // 过滤空值
            $file_url = array_map(function($path) use ($new_filename) {
                return $path . '/20cms/' . $new_filename;
            }, $paths);
            if(empty($file_url)) {
                $file_url = $_G['siteurl'] . 'source/plugin/erling_filedset/20cms/' . $new_filename;
            }
        } else {
            $file_url = $configs['path_before']['value'] . '/20cms/' . $new_filename;
        }
    } else {
       $file_url = $_G['siteurl'] . 'source/plugin/erling_filedset/20cms/' . $new_filename; 
    }

    if(!$is_cover) {
        $er_filedset = C::t('#erling_filedset#er_filedset');
        $insert_id = $er_filedset->insert([
            'uid' => $_G['uid'],
            'title' => $file['name'],
            'url' => '20cms/'. $new_filename
        ]);

        if(!$insert_id) {
            echo json_encode([
                'success' => false,
                'message' => '数据库插入失败',
                'insert_id' => $insert_id,
            ]);
            exit;
        }
    }

    echo json_encode([
        'success' => true,
        'message' => '文件上传成功',
        'file_url' => $file_url
    ]);
} else {
    echo json_encode(['success' => false, 'message' => '文件上传失败']);
}